import Web3 from "web3";
import Contract from "../../build/contracts/Election.json"

/**
 * 创建web3对象，生成合约实例
 */
var web3;
if (window.ethereum) {
    // use MetaMask's provider
    web3 = new Web3(window.ethereum);
    window.ethereum.enable(); // get permission to access accounts
} else {
    App.web3 = new Web3(
        new Web3.providers.HttpProvider("http://127.0.0.1:7545"),
    );
}
/**
 * 部署合约的abi和address
 */
var contract = new web3.eth.Contract(Contract.abi, "0xaecf92d6f96a8ebd78ba3a3fa9dc60f762d20d12");
/**
 * 获取所有账户
 */
// web3.eth.getAccounts().then(console.log);
/**
 * 设置当前账户相关信息
 */
var currentAccount;
web3.eth.getAccounts().then(function (result) {
    currentAccount = result[0];
    document.getElementById("currentAccount").innerText = currentAccount;
    contract.methods.getCurrent(currentAccount).call(function (err, result) {
        // console.log(result);
        if (result != "" || result != undefined) {
            addCurrentHistory(result);
        }
    });
    /**
     * 判断是否是合约创造者
     */
    // contract.methods.isCreator(currentAccount).call(function(err,result) {
    //     console.log(result);
    // })
});
/**
 * 点击购票
 */
document.getElementById("buyBt").onclick = function () {
    // web3.eth.personal.unlockAccount(currentAccount, "888");
    contract.methods.purchase().send({
        from: currentAccount, //自己的账户地址
        gas: 500000,
        gasPrice: "1",
        value: 1000000000000000000 //价格 1 ether
    }, function (err, result) {
        document.getElementById("canVote").innerText = 1;
        console.log("result:" + result);
        console.log("err:" + err)
    });
}
/**
 * 添加候选人
 */
document.getElementById("addBt").onclick = function () {
    var name = document.getElementById("name").value;
    var number = document.getElementById("number").value
    /**
     * 添加于合约内部
     */
    contract.methods.addCandidate(name, Number(number)).send({
        from: currentAccount, //直接用有钱的账户来支付
        gas: 500000,
        gasPrice: "1",
    }, function (err, result) {
        addRow(name, number);
        console.log(result);
    })
};
/**
 * 确认投票
 */
document.getElementById("submitBt").onclick = function () {
    var obj = document.getElementById("dropBt");
    var index = obj.selectedIndex;
    var value = obj.options[index].value;
    contract.methods.vote(value).send({
        from: currentAccount,
        gas: 500000,
        gasPrice: "1",
    }, function (err, result) {
        document.getElementById("canVote").innerText = 0;
        document.getElementById("personTable").rows[value].cells[2].innerText++;
        addHistory(currentAccount, obj.options[index].innerText);
        addCurrentHistory(obj.options[index].innerText);
    });
}
/**
 * 所有的历史记录
 */
contract.methods.getHistoryCount().call(function (err, result) {
    for (let i = 1; i <= result; i++) {
        contract.methods.getHistory(i).call(function (err, result) {
            addHistory(result[0], result[1]);
        })
    }
})
/**
 * 新增投票历史记录
 */
function addHistory(addr, candidateName) {
    var historyTable = document.getElementById("historyTable");
    var rs = historyTable.rows; //table取到所有的行
    var insertR = historyTable.insertRow(rs.length); //给表格添加一行(不包单元格)
    var c0 = insertR.insertCell(0);
    c0.innerHTML = addr;
    var c1 = insertR.insertCell(1);
    c1.innerHTML = candidateName;
    var c2 = insertR.insertCell(2);
    c2.innerHTML = 1;
}
/**
 * 候选人列表
 */
contract.methods.getCandidateCount().call(function (err, result) {
    for (let i = 1; i <= result; i++) {
        contract.methods.getCandidate(i).call(function (err, result) {
            addRow(result[0], result[1]);
        })
    }
})
/**
 * 当前账户投票历史
 */

function addCurrentHistory(candidateName) {
    var currentHistoryTable = document.getElementById("currentHistoryTable");
    var rs = currentHistoryTable.rows; //table取到所有的行
    var insertR = currentHistoryTable.insertRow(rs.length); //给表格添加一行(不包单元格)
    var c0 = insertR.insertCell(0);
    c0.innerHTML = currentAccount;
    var c1 = insertR.insertCell(1);
    c1.innerHTML = candidateName;
    var c2 = insertR.insertCell(2);
    c2.innerHTML = 1;
}
/**
 * 对普通账户隐藏操作栏
 */
// ElectionContract.methods.isCreator().call(function (err, result) {
//     // if (!result) {
//     //     document.getElementById("operationColumn").style.display = "none";
//     // }else{

//     // }
//     console.log(result);
// })
// contract.methods.isCreator().call(function (err, result) {
//     console.log(result);
// })
// contract.methods.myAddr().call({ from: currentAccount }, function (err, result) {
//     console.log("myAddr: " + result);
//     console.log(currentAccount)
// })
/*-----------------------*/
var value = 1;
function addRow(name, number) {
    var personList = document.getElementById("dropBt");
    var option = document.createElement("option");
    option.innerText = name;
    option.value = value;
    personList.appendChild(option);
    var personList1 = document.getElementById("dropA");
    var option1 = document.createElement("option");
    option1.innerText = name;
    option1.value = value++;
    personList1.appendChild(option1);
    var personTable = document.getElementById("personTable");
    var rs = personTable.rows; //table取到所有的行
    var insertR = personTable.insertRow(rs.length); //给表格添加一行(不包单元格)
    //insertR.innerHTML = rs[1].innerHTML; 
    var c1 = insertR.insertCell(0);
    c1.innerHTML = rs.length - 1;
    var c2 = insertR.insertCell(1);
    c2.innerHTML = name;
    var c3 = insertR.insertCell(2);
    c3.innerHTML = number;
    var c4 = insertR.insertCell(3);
    c4.innerHTML = '<input type="button" value="去除资格" class="del btn btn-primary btn-sm"/>';
    doOperator();
}
function doOperator() {
    var dels = document.getElementsByClassName('del');
    var personTable = document.getElementById('personTable');
    var personList = document.getElementById("dropBt");
    var personList1 = document.getElementById("dropA");
    for (var i = 0; i < dels.length; i++) {
        dels[i].onclick = function () {
            if (confirm("是否确定去除此人资格？")) { //提示是否删除
                var option = personList.childNodes.item(this.parentNode.parentNode.rowIndex);
                var li1 = personList1.childNodes.item(this.parentNode.parentNode.rowIndex);
                personList.removeChild(option);
                personList1.removeChild(li1);
                personTable.deleteRow(this.parentNode.parentNode.rowIndex);
            }
        }
    }
}